package handler

import (
	"article-hub/cache"
	"article-hub/model"
	"article-hub/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "login_error" + username
	cachejson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cachejson >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "已经错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ? ", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "该用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cachejson == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 400,
		"msg":  "登陆成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var users []model.User
	redis_key := "list_users" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cachejson == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&users)
		jsonData, _ := json.Marshal(&users)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &users)
	}
	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 400,
		"msg":  "展示成功",
		"data": gin.H{
			"users": users,
			"total": total,
		},
	})
	return
}
